package com.aj.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.aj.activity.adapter.ChoosePhotoAdapter;
import com.aj.activity.adapter.ChoosePhotoAdapter.FileHodler;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.AddPhotoRequest;
import com.aj.http.request.UploadPhotoRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.UploadPhotoResponse;
import com.aj.utils.Contants;

/**
 * The Class ChoosePhotoActivity.
 */
public class ChoosePhotoActivity extends BaseActivity {

	/** The instance. */
	public static ChoosePhotoActivity instance = null;

	public Integer uploadfileSuccessCount = 0;

	public Integer uploadfileFailCount = 0;

	/** The Constant TAG. */
	private final static String TAG = ChoosePhotoActivity.class.getName();
	/** The page flag. */
	public static String pageFlag = "CHOOSEPHOTO";

	/** The filegridview. */
	private GridView photo_body;

	/** The adapter. */
	private ChoosePhotoAdapter adapter;

	/** The dir path. */
	private String dirPath = "";

	/** The Constant PHOTO_FILETYPE. */
	private static final int PHOTO_FILETYPE = 0;

	/** The Constant VEDIO_FILETYPE. */
	private static final int VEDIO_FILETYPE = 1;

	/** The filter. */
	private String filter = "";

	/** The Constant UPDATE_MESSAGE. */
	private final static int UPDATE_MESSAGE = 0X9900;

	/** The photo file list. */
	private final List<String> photoFilePathList = new ArrayList<String>();

	/**
	 * On create.
	 * 
	 * @param savedInstanceState
	 *            the saved instance state
	 * @version
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_choose_photo);
		instance = this;
		initView();
	}

	/**
	 * Inits the view.
	 * 
	 * @version
	 */
	private void initView() {
		pageFlag = getIntent().getStringExtra(Contants.PAGEFLAG_STRING);
		int fileType = PHOTO_FILETYPE;
		if (pageFlag == null || pageFlag.trim().equals("")) {
			pageFlag = Contants.PAGEFLAG_STRING;
		}

		if (pageFlag.trim().equals(Contants.TYPE_CHOOSEPHOTO)) {
			fileType = PHOTO_FILETYPE;
		} else {
			fileType = VEDIO_FILETYPE;
		}
		dirPath = getIntent().getStringExtra(Contants.DIR_PATH_PARAMS);

		photo_body = (GridView) findViewById(R.id.photo_body);

		String title = "";
		if (dirPath != null && !dirPath.trim().equals("")) {
			title = dirPath.substring(dirPath.lastIndexOf("/") + 1);
		}
		setActionBarTitle(title);
		if (pageFlag.trim().equals("CHOOSEPHOTO")) {
			filter = "image/jpeg,image/png,image/x-ms-bmp,image/jpg,image/gif,"
					+ dirPath;
			findFileBySys(dirPath, filter);
		} else if (pageFlag.trim().equals("CHOOSEVEDIO")) {
			filter = "video/3gpp," + dirPath;
			findFileBySys(dirPath, filter);
		}

		adapter = new ChoosePhotoAdapter(photo_body, ChoosePhotoActivity.this,
				photoFilePathList, fileType);
		ItemClickEvent itemClickEvent = new ItemClickEvent();
		ButtonClickEvent buttonClickEvent = new ButtonClickEvent();
		setRightTextAndClickEvent1(getString(R.string.finish_text),
				buttonClickEvent);
		photo_body.setAdapter(adapter);
		photo_body.setOnItemClickListener(itemClickEvent);
	}

	/**
	 * 根据过滤条件生成文件过滤结果集（使用系统图库）.
	 * 
	 * @param filePath
	 *            the file path
	 * @param filter
	 *            the filter
	 * @version
	 */
	private void findFileBySys(String filePath, String filter) {
		Uri mImgUri;
		if (filter.indexOf("image") != -1 && filter.indexOf("video") == -1) {
			mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		} else if (filter.indexOf("image") == -1
				&& filter.indexOf("video") != -1) {
			mImgUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		} else {
			mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}

		ContentResolver mContentResolver = instance.getContentResolver();
		String[] selectionArgs = filter.split(",");

		String selection = "";

		for (int i = 0; i < selectionArgs.length - 1; i++) {
			selection += MediaStore.Images.Media.MIME_TYPE + "=? or ";
		}
		selection = selection.substring(0, selection.lastIndexOf(" or"));

		selection = "( " + selection + ")";

		selection += " and substr(" + MediaStore.Images.Media.DATA + ",1,"
				+ filePath.length() + ") = ?";
		// new String[] {"image/jpeg", "image/png"}
		Cursor mCursor = mContentResolver.query(mImgUri, null, selection,
				selectionArgs, MediaStore.Images.Media.DATE_MODIFIED + " DESC");

		if (mCursor == null) {
			return;
		}

		while (mCursor.moveToNext()) {
			String path = mCursor.getString(mCursor
					.getColumnIndex(MediaStore.Images.Media.DATA));
			File file = new File(path);
			String parentPath = file.getParentFile().getAbsolutePath();
			if (file.length() <= 5 * 1024 * 1024 && file.length() > 0
					&& parentPath.trim().equals(filePath)) {
				photoFilePathList.add(file.getAbsolutePath());
			}
		}

	}

	/**
	 * The Class ButtonClickEvent.
	 */
	class ButtonClickEvent implements OnClickListener {

		/**
		 * On click.
		 * 
		 * @param v
		 *            the v
		 * @version
		 */
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.righttext_1:
				if (adapter != null && adapter.getChoosePathList() != null
						&& adapter.getChoosePathList().size() > 0) {
					final List<String> filePathList = adapter
							.getChoosePathList();
					showProgressDialog();
					new Thread() {
						@Override
						public void run() {
							for (String filePath : filePathList) {
								new UploadPhotoRequest().excuteSync(
										ChoosePhotoActivity.this, null, null,
										"JPEG", new File(filePath),
										new IHttpCallBack() {
											@Override
											public void success(String result) {
												UploadPhotoResponse response;
												try {
													response = new UploadPhotoResponse(
															new JSONObject(
																	result));
													Common common = response
															.getCommon();
													if (common != null
															&& common
																	.getReturnCode()
																	.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
														new AddPhotoRequest()
																.excuteSyn(
																		getApplicationContext(),
																		getIntent()
																				.getStringExtra(
																						Contants.USER_ID_PARAMS),
																		getIntent()
																				.getStringExtra(
																						Contants.ZONE_ID_PARAMS),
																		response.getPhotoUrl(),
																		new IHttpCallBack() {
																			@Override
																			public void success(
																					String result) {
																				try {
																					Common common = new Common(
																							new JSONObject(
																									result));
																					if (common
																							.getReturnCode() != null
																							&& common
																									.getReturnCode()
																									.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
																						uploadfileSuccessCount++;
																					} else {
																						uploadfileFailCount++;
																					}
																				} catch (JSONException e) {
																					e.printStackTrace();
																					uploadfileFailCount++;
																				}
																			}

																			@Override
																			public void fail(
																					String result) {
																				uploadfileFailCount++;
																			}
																		});
													} else {
														uploadfileFailCount++;
													}
												} catch (JSONException e) {
													uploadfileFailCount++;
												}

											}

											@Override
											public void fail(String result) {
												uploadfileFailCount++;
											}

										});
							}
							handler.sendEmptyMessage(0x00001);
						}
					}.start();

					break;
				}
			}
		}
	}

	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0x00001:
				Toast.makeText(
						getApplicationContext(),
						"上传成功：" + uploadfileSuccessCount + ",失败："
								+ uploadfileFailCount, Toast.LENGTH_LONG)
						.show();
				Intent intent = new Intent();
				intent.setAction(Contants.REFRESH_PERSION_ALBUM_ACTION);
				sendBroadcast(intent);
				dimissProgressDialog();
				finish();
				if (DirExplorerActivity.instance != null) {
					DirExplorerActivity.instance.finish();
					DirExplorerActivity.instance = null;
				}
				break;
			default:
				break;
			}

			return true;
		}
	});

	/**
	 * The Class ItemClickEvent.
	 */
	class ItemClickEvent implements OnItemClickListener {

		/**
		 * On item click.
		 * 
		 * @param arg0
		 *            the arg0
		 * @param arg1
		 *            the arg1
		 * @param arg2
		 *            the arg2
		 * @param arg3
		 *            the arg3
		 * @version
		 */
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if (arg1.getTag() != null) {
				FileHodler fileHodler = (FileHodler) arg1.getTag();
				if (fileHodler.getCheckbox_image().isChecked()) {
					fileHodler.getCheckbox_image().setChecked(false);
				} else {
					fileHodler.getCheckbox_image().setChecked(true);
				}
				List<String> filePathList = adapter.getChoosePathList();
				for (String s : filePathList) {
					Log.e(TAG, "s file paht:" + s);
				}
			}
		}
	}

	/**
	 * On resume.
	 * 
	 * @version
	 */
	@Override
	protected void onResume() {
		super.onResume();
	}

}
